package com.chengqj;

import com.chengqj.dao.UserDO;
import com.chengqj.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.Optional;

/**
 * Copyright © 2020年 com.qxkj. All rights reserved.
 *
 * @author chengqj
 * 编程式事务
 * version 1.0.0 (接口必须带上)
 * @date 2020/11/5 16:43
 */
@Service
public class UserServiceTxInCode {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private PlatformTransactionManager transactionManager;

    /**
     * 编程式事务正常实现
     * @param userDO
     * @return
     */
    public UserDO createCommit(UserDO userDO) {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        //设置隔离机制
        def.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
        //设置传播机制
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        //设置超时时间
        def.setTimeout(15);
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            userDO.setUsername("Code:" + userDO.getUsername());
            userRepository.save(userDO);
            transactionManager.commit(status);
            return userDO;
        } catch (Exception e) {
            transactionManager.rollback(status);
            throw e;
        }
    }

    /**
     * 编程式事务异常回滚实现
     * @param userDO
     * @return
     */
    public UserDO createRollback(UserDO userDO) {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        //设置隔离机制
        def.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
        //设置传播机制
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        //设置超时时间
        def.setTimeout(15);
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            userDO.setUsername("Code:" + userDO.getUsername());
            userRepository.save(userDO);
            int i = 1/0;
            transactionManager.commit(status);
            return userDO;
        } catch (Exception e) {
            transactionManager.rollback(status);
            throw e;
        }
    }

    /**
     * 获取用户数据
     * @param id
     * @return
     */
    public UserDO getUserById(Long id) {
        Optional<UserDO> userOptional = userRepository.findById(id);
        if (userOptional.isPresent()){
            return userOptional.get();
        }
        return null;
    }
}
